package com.qf.intercepioirs;/*
 *徐韬
 *2021/10/28
 *15:10
 */

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.constons.resultCode;
import com.qf.dto.R;
import com.qf.pojo.TAdminUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@Component
public class LoginInterceptor implements HandlerInterceptor {
    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }


    @Override
    //前置通知
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean login = request.getSession().getAttribute("user") != null;
        if (!login) {
            R error = R.setError(resultCode.NO_LOGIN, "请先登录", null);
            response.setContentType("application/json;charset=utf-8");
           response.getWriter().println(objectMapper.writeValueAsString(error));
        }
        return login;
    }
//后置通知
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {


    }
//处理完最后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
